#include <Network/RootRequestHandlerFactory.h>

#include <Network/P2PGetSessionRequestHandler.h>

#include <Poco/Format.h>
#include <Poco/Net/HTTPServerRequest.h>
#include <Poco/URI.h>
#include <iostream>
using namespace Poco::Net;
using namespace Network;

CRootRequestHandlerFactory::CRootRequestHandlerFactory(void)
{
}

CRootRequestHandlerFactory::~CRootRequestHandlerFactory(void)
{
}

void CRootRequestHandlerFactory::Setup(Poco::AutoPtr<Poco::Util::AbstractConfiguration> aConfiguration)
{
	try
	{
		std::cout<<"setup root factory";
		iRequestDynFactory.registerClass<P2PGetSessionRequestHandler> ("P2PGetSessionRequestHandler");



		std::cout<<"setup root factory";		
		int aIndex = 0;
		iURITemplateList.clear();
		for (;;aIndex ++)
		{
		
			std::cout<<aIndex;
		
			std::string aKey = "HTTPRequestHandler";
			if (aIndex > 0)
				aKey = aKey+ Poco::format("[%d]" , aIndex);
			std::string aURIKey = aKey+ ".URIKey";
			std::string aClassKey = aKey + ".class";

			iURITemplateList[aConfiguration->getString(aURIKey) ] = aConfiguration->getString(aClassKey); 
		}
	}
	catch (...)
	{
		
	}
}

template <class THandler>
THandler* CRootRequestHandlerFactory::CheckURIAndCreateHandler(const std::string& aURI, const std::string& aTemplateURI)
{
	if (aURI.length() > aTemplateURI.length() && aURI.substr(0, aTemplateURI.length() ) == aTemplateURI )
		return new THandler;
	return NULL;
}

Poco::Net::HTTPRequestHandler* CRootRequestHandlerFactory::CreateRequestFromURI(const std::string& aURI , const std::string& aTemplateURI , const std::string& aClassName)
{
	std::cout<<"Poco::Net::HTTPRequestHandler* CRootRequestHandlerFactory::CreateRequestFromURI "<<aURI<<" "<<aTemplateURI;
	try {
		if (aURI.length() > aTemplateURI.length() && aURI.substr(0, aTemplateURI.length() ) == aTemplateURI )
			return iRequestDynFactory.createInstance(aClassName);
	}
	catch(...)
	{
		return NULL;
	}
	return NULL;

}

Poco::Net::HTTPRequestHandler* CRootRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest& request)
{

	//std::cout<<"Create request RootStart"<<std::endl;
	Poco::Net::HTTPRequestHandler* aHandler = NULL;
	//CreateRequestHandlerNotification* aNotification = new CreateRequestHandlerNotification(request , aHandler);



	//iRequestCenter.postNotification(aNotification);
	//if (aHandler != NULL)
	//	return aHandler;

	std::string aURI = request.getURI();

	std::map<std::string , std::string>::const_iterator aIt = iURITemplateList.begin();
	for (; aIt != iURITemplateList.end(); aIt ++)
	{
		aHandler = CreateRequestFromURI(aURI , aIt->first , aIt->second );
		if (aHandler)
			return aHandler;
	}
	



	return aHandler;
}
